package slide_window

import (
	"context"
	_ "embed"
	"ratelimit"
	"time"

	"github.com/go-redis/redis/v8"
)

//go:embed redis_slide_window.go
var slideWindowLua string

type RedisSlideWindowLimit struct {
	client *redis.Client
	window time.Duration
	limit  int64
	key    string
}

func NewRedisSlideWindowLimit(client *redis.Client, window time.Duration, limit int64, key string) ratelimit.Limiter {
	return &RedisSlideWindowLimit{
		client: client,
		window: window,
		limit:  limit,
		key:    key,
	}
}

func (r *RedisSlideWindowLimit) Allow() bool {
	ctx := context.Background()
	now := time.Now().UnixNano() / 1e6
	windowMs := r.window.Milliseconds()
	cmd := r.client.Eval(ctx, slideWindowLua, []string{r.key}, windowMs, r.limit, now)
	result, err := cmd.Result()
	if err != nil {
		return false
	}
	return result == "true"
}
